﻿
using Base.ClientUI;
using System;
using System.Collections.Generic;
using System.Reflection.Emit;
using Base.WCS.Common;
using Base.WCS.Entity;
using System.Windows.Forms;
using System.Reflection;
using Microsoft.VisualBasic;
using Base.Common;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using HBase;

namespace Base.ClientUI {
    public partial class TaskViewFrms :UITitlePage {
          DateTime time1 = new DateTime(1999 ,2 ,2);
        DateTime time2 = new DateTime(1999 ,2 ,2);
        DateTime time3 = new DateTime(1999 ,2 ,2);
        public TaskViewFrms() {
            InitializeComponent();
            InitGridColumn();
            InitDictionary();
            dataGridViewComplete.AutoGenerateColumns = false;
            dataGridViewParam.AutoGenerateColumns = false;
            dataGridViewCarrier.AutoGenerateColumns = false;
        }
        protected override CreateParams CreateParams {
            get {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000; // 用双缓冲绘制窗口的所有子控件
                return cp;
            }
        }
        /// <summary>
        /// GridView初始化
        /// </summary>
        private void InitGridColumn() {
             dataGridViewComplete.AddColumn("ID" ,"id").Visible = false;
 
             dataGridViewComplete.AddColumn("信息" ,"info").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        
             dataGridViewComplete.ReadOnly = true;
            

            dataGridViewCarrier.AddColumn("ID" ,"ID").Visible = false;
            dataGridViewCarrier.AddColumn("设备类型" ,"className").SetFixedMode(85);
            dataGridViewCarrier.AddColumn("任务号" ,"taskNo").SetFixedMode(80);
            dataGridViewCarrier.AddColumn("状态" ,"status").SetFixedMode(85);
            dataGridViewCarrier.AddColumn("描述" ,"Extra").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridViewCarrier.AddColumn("顺序" , "priority").SetFixedMode(100);
       
            dataGridViewCarrier.ReadOnly = true;
             dataGridViewParam.AddColumn("ID" ,"id").Visible = false;
           // dataGridViewParam.AddColumn("信息" ,"param").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridViewParam.AddColumn("当前起始" ,"cStn").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridViewParam.AddColumn("当前目标" ,"cDes").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridViewParam.AddColumn("起始" ,"src").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridViewParam.AddColumn("目标" ,"des").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            //dataGridViewParam.AddColumn("状态" ,"status").SetFixedMode(85);
            //dataGridViewParam.AddColumn("类型" ,"type").SetFixedMode(100);

            dataGridViewParam.ReadOnly = true;
        }
         /// <summary>
        /// 字典值缓存
        /// </summary>
        private void InitDictionary() {
         }
         public override void Init() {
            base.Init();
            PageGridSource();
            dataGridViewComplete.AutoGenerateColumns = false;
            dataGridViewParam.AutoGenerateColumns = false;
            dataGridViewCarrier.AutoGenerateColumns = false;
            //InitGridCarrier();          
        }
         private void PageGridSource() {
            var list = HttpTaskUtil.getComplete();
            if( list == null ) {
                //this.ShowErrorTip("网络不稳定!");
                return;
            }
            var res = new List<Complete>();
            
            String t = textBox2.Text;

            foreach (Complete c in list) {
                if (String.IsNullOrEmpty(t)||c.boxCode.IndexOf(t) != -1) {
                    res.Add(c);
                }
            }
            uiPagination1.DataSource = res;
            uiPagination1.ActivePage = 1;
        }
         private void uiPagination1_PageChanged(object sender ,object pagingSource ,int pageIndex ,int count) {
            dataGridViewComplete.DataSource = pagingSource;
            InitGridCarrier();
        }
        
         /// <summary>
        /// 加载任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnloadComplete_Click(object sender ,System.EventArgs e) {
            uiPagination1.ActivePage = 0;
            PageGridSource();
            InitGridCarrier();
            // InitGridParam();
        }
         private void InitGridParam() {
            var list = HttpTaskUtil.GetCompleteParam(1);
            if( list == null ) {
                return;
            }
            dataGridViewParam.DataSource = list;
        }
         private void InitGridCarrier() {
            if( dataGridViewComplete == null || dataGridViewComplete.Rows.Count == 0 ) {
                return;
            }
            int selectcomplateId = Convert.ToInt32(dataGridViewComplete.Rows[dataGridViewComplete.CurrentRow.Index].Cells["id"].Value);
            loadSubTask(selectcomplateId);
            dataGridViewCarrier_CellClick(null ,null);
        }
        private void craneGridButton_Click(object sender ,System.EventArgs e) {
            DateTime time = new DateTime();
            time = DateTime.Now;
            TimeSpan t = time - time1;
            if( t.Minutes > 5 ) {
                 string result = "";
                bool b = UIInputDialog.InputPasswordDialog(this ,ref result ,false);
                string password = HttpSysUtil.pass;
                if( result != password ) {
                    if( result != "" )
                        UIMessageDialog.ShowErrorDialog(this ,"密码输入错误，不能进行删除操作！");
                    return;
                } else {
                    time1 = DateTime.Now;
                 }
            }
             if( dataGridViewComplete.Rows.Count <= 0 ) {
                return;
            }
            if( dataGridViewParam.Rows.Count <= 0 ) {
                return;
            }
            long selectcomplateId = Convert.ToInt64(dataGridViewComplete.Rows[dataGridViewComplete.CurrentRow.Index].Cells["id"].Value);
            int taskNo = Convert.ToInt32(label1.Text);

            if( this.ShowAskDialog("确定要删除该任务？") ) {
                bool deleteTask = HttpTaskUtil.DeleteCraneAndCarrierTask(taskNo);
                loadSubTask(selectcomplateId);
                if( deleteTask ) {
                  
                    this.ShowSuccessTip("删除成功!");
                } else {
                    this.ShowErrorTip("删除失败!");
                }
            } else {
                this.ShowErrorTip("您点击了取消按钮");
            }
        }
          public void loadSubTask(long selectcomplateId) {
             JObject data = HttpTaskUtil.getAllTaskByCompleteId(selectcomplateId);
            if( data == null ) {
                return;
            }
            List<CompleteParam> completes = JsonConvert.DeserializeObject<List<CompleteParam>>(data["completeParam"].ToString());
            dataGridViewParam.DataSource = completes;
            dataGridViewCarrier.DataSource = getTask(data);
         }
         public virtual List<BaseTask> getTask(JObject data) {
             List<TaskCrane> craneList = getTask<TaskCrane>(data);
             List<TaskCarrier> carrierList = getTask<TaskCarrier>(data);
     
            List<BaseTask> res = TaskUtil.margin(craneList ,carrierList);

           
            return res;
         }
        public static List<T> getTask<T>(JObject data) where T : BaseTask {
            String className = typeof(T).Name;
            string deviceType = className.Substring(4);
            JToken cranelist = data["task" + deviceType];
             List<T> list = JsonConvert.DeserializeObject<List<T>>(cranelist.ToString());
            foreach( T t in list ) {
                t.className = className;
            }
            return list;
        }
       
         /// <summary>
         /// 任务完成
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="e"></param>
        private void csxfinsh_Click(object sender ,EventArgs e) {
            DateTime time = DateTime.Now;
            TimeSpan t = time - time3;
            if( t.Minutes > 5 ) {
                 string result = "";
                UIInputDialog.InputPasswordDialog(this ,ref result ,false);
                string password = HttpSysUtil.pass;
                if( result != password ) {
                    if( result != "" )
                        UIMessageDialog.ShowErrorDialog(this ,"密码输入错误，不能进行完成操作！");
                     return;
                } else {
                    time3 = DateTime.Now;
                }
            }
            if( dataGridViewCarrier.Rows.Count <= 0 ) {
                return;
            }
         
            if( !this.ShowAskDialog("确定任务已完成？") ) {
                return;
            }
            int taskNo = Convert.ToInt32(label1.Text);
            String flag = HttpTaskUtil.finishTaskById(textBox1.Text ,taskNo);
            if( flag.ToLower() == "true" ) {
                this.ShowSuccessTip("操作成功!");
            } else {
                this.ShowErrorTip(flag);
            }
            InitGridCarrier();
        }
        
     
         private void dataGridViewComplete_CellFormatting(object sender ,System.Windows.Forms.DataGridViewCellFormattingEventArgs e) {
            int rowIndex=e.RowIndex;
            var data = dataGridViewComplete.DataSource;
            List<object> list = (List<object>)data;
            Complete c = (Complete)list[rowIndex];
            int loc = 0;
            if (c.src > 10000)
            {
                loc = c.src;
            }
            else {
                loc = c.des; 
            }
            loc = (loc + 100000) / 200000;
            object value =c.priority+"巷道:"+ loc+"条码:" +c.boxCode + c.info+ "[" + TimeUtil.seconds2DateSring(c.createTime)+"]" ;
            e.Value = value;
        }
        private static string change(String type ,String name ,object value) {
            if( value == null ) {
                return "";
            }
            if( value.GetType() == typeof(DateTime) ) {
                if( (( DateTime ) value).Ticks == 0 ) {
                    return "";
                }
                 if( type == "complete" ) {
                    return TimeUtil.seconds2DateSring(value);
                } else {
                    return TimeUtil.seconds2TimeSring(value);
                }
             }
            String key = type + "." + name.ToLower() + ".";
             return TaskUtil.getDisplayName(key ,value.ToString());
         }
           private void dataGridViewCarrier_CellFormatting(object sender ,System.Windows.Forms.DataGridViewCellFormattingEventArgs e) {
            string name = dataGridViewCarrier.Columns[e.ColumnIndex].DataPropertyName;
            e.Value = change("detail" ,name ,e.Value);
        }
         private void dataGridViewCarrier_CellClick(object sender ,DataGridViewCellEventArgs e) {
            if( dataGridViewCarrier.Rows.Count <= 0 ) {
                return;
            }
            if( e == null ) {
                return;
            }
            List<BaseTask> res = ( List<BaseTask> ) dataGridViewCarrier.DataSource;
            DataGridViewCell cell = dataGridViewCarrier.CurrentRow.Cells[e.ColumnIndex];
            
            BaseTask bt = res[dataGridViewCarrier.CurrentRow.Index];
           
            label1.Text = bt.taskNo + "";
            int des = 0;
            if( !int.TryParse(cell.Value.ToString() ,out des) ) {
                textBox1.Text = bt.des + "";

            } else {
                textBox1.Text = des + "";

            }
        
        }

        private void dataGridViewParam_CellClick(object sender ,DataGridViewCellEventArgs e) {
            if( dataGridViewParam.Rows.Count <= 0 ) {
                return;
            }
            if( e == null ) {
                return;
            }

            List<CompleteParam> completes = ( List<CompleteParam> ) dataGridViewParam.DataSource;
            DataGridViewCell cell = dataGridViewParam.CurrentRow.Cells[e.ColumnIndex];

            CompleteParam bt = completes[dataGridViewParam.CurrentRow.Index];
           
            label1.Text = bt.taskNo + "";
            int des = 0;
            object v = cell.Value;
            v = v == null ? 1 : v;
            if( !int.TryParse(v.ToString() ,out des) ) {
                textBox1.Text = bt.des + "";
            } else {
                textBox1.Text = des + "";

            }

        }
        private void dataGridViewParam_CellFormatting(object sender ,DataGridViewCellFormattingEventArgs e) {
            string name = dataGridViewParam.Columns[e.ColumnIndex].DataPropertyName;
            e.Value = change("CompleteParam" ,name ,e.Value);
        }
        private void dataGridViewComplete_CellClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            if (dataGridViewComplete.Rows.Count <= 0 && e.RowIndex < 0)
            {
                return;
            }
            InitGridCarrier();
        }
        private void dataGridViewComplete_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridViewComplete == null || dataGridViewComplete.Rows.Count == 0)
            {
                return;
            }
            int selectcomplateId = Convert.ToInt32(dataGridViewComplete.Rows[dataGridViewComplete.CurrentRow.Index].Cells["id"].Value);
            HttpTaskUtil.updatePriority(selectcomplateId);
            PageGridSource();
        }

        private void dataGridViewComplete_MouseUp(object sender, MouseEventArgs e) {
            
                if (e.Button == MouseButtons.Right) {
                if (dataGridViewComplete == null || dataGridViewComplete.Rows.Count == 0) {
                    return;
                }
                int selectcomplateId = Convert.ToInt32(dataGridViewComplete.Rows[dataGridViewComplete.CurrentRow.Index].Cells["id"].Value);
                HttpTaskUtil.updatePriority(selectcomplateId);
                PageGridSource();


            }
          
        }
    }
}